package redis

import (
	"context"
	"fmt"
	"time"

	"github.com/redis/go-redis/v9"

	"mxshop_srvs/inventory_srv/setting"
)

// Redis defines a redis dao.
type Redis struct {
	rdb *redis.Client
}

// NewRedis creates a redis dao.
func NewRedis(rdb *redis.Client) *Redis {
	return &Redis{
		rdb: rdb,
	}
}

func Init() (rdb *redis.Client, err error) {
	redisConf := setting.Conf.RedisConfig
	rdb = redis.NewClient(&redis.Options{
		Addr:     fmt.Sprintf("%s:%d", redisConf.Host, redisConf.Port),
		Password: redisConf.Password, // no password set
		DB:       redisConf.DB,       // use default DB
	})

	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
	defer cancel()

	_, err = rdb.Ping(ctx).Result()
	return rdb, err
}
